<template>
  <div class="main-content" id="container">
    <div class="screen-frame clearfix">
      <div class="col-md-6 col-lg-5">
        <div class="form-horizontal">
          <div class="form-group">
            <label for class="col-md-3 col-sm-2 control-label">客户：</label>
            <div class="col-md-8 col-sm-10">
              <input
                type="text"
                class="form-control"
                placeholder="请输入客户姓名/联系电话"
                v-model="params.searchContent"
              />
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label for class="col-md-3 col-sm-2 control-label">交易状态：</label>
            <div class="col-md-8 col-sm-10">
              <select class="form-control" v-model="params.confirmStatus">
                <option value>全部</option>
                <option v-for="(row, index) in confirmArray" v-bind:value="index">{{row}}</option>
              </select>
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label class="col-md-3 col-sm-2 control-label">报备时间：</label>
            <div class="col-md-8 col-sm-10" style="width:73%">
              <input
                type="date"
                class="form-control"
                style="width:45%;float:left"
                v-model="params.createTimeBefore"
              />
              <span style="float:left">-</span>
              <input
                type="date"
                class="form-control"
                style="width:45%;float:left"
                v-model="params.createTimeAfter"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-6 col-lg-5">
        <div class="form-horizontal">
          <div class="form-group">
            <label for class="col-md-4 col-sm-2 control-label">楼盘名称：</label>
            <div class="col-md-8 col-sm-10">
              <input
                type="text"
                class="form-control"
                placeholder="请输入楼盘名称"
                v-model="params.premisesName"
              />
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label for class="col-md-4 col-sm-2 control-label">报备状态：</label>
            <div class="col-md-8 col-sm-10">
              <select class="form-control" v-model="params.customerStatus">
                <option value>全部</option>
                <option v-for="(row, index) in customerArray" v-bind:value="index">{{row}}</option>
              </select>
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label for class="col-md-4 col-sm-2 control-label">门店组别：</label>
            <div class="col-md-8 col-sm-10">
              <input
                type="text"
                class="form-control"
                placeholder="请输入门店组别"
                v-model="params.storeOrGroup"
              />
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div style="margin-left: 27%;text-align: right;margin-bottom: 10px;">
            <button
              type="button"
              v-on:click="list(1)"
              class="btn screen-submit"
              style="position: initial;margin-right: 20px;"
            >查询</button>
            <button
              type="button"
              class="btn btn-theme"
              style="background-color: #0099cc;"
              v-on:click="openBatchSaveModal"
            >批量报备</button>
            <button
                type="button"
                v-on:click="exportList"
                class="btn screen-submit"
                style="position: initial;margin-left: 20px;"
            >导出</button>
            <a :href="exportUrl" v-show="exportBtnShow" download="巧分销报备导出.xlsx" style="color: yellowgreen; padding-left: 20px;">
              点击下载
              <Icon type="md-cloud-download" size="16" />
            </a>
          </div>
        </div>
      </div>
    </div>
    <div class="table-responsive report-table">
      <Table stripe border :columns="tableConfig" :data="customerPremisesList"></Table>
    </div>
    <div id="laypage_div"></div>
    <Modal></Modal>
    <addAppealModal v-bind:appealModal="appealInfo" v-on:saveAppealListener="saveAppealReturn"></addAppealModal>
    <addReportModal v-bind:reportModal="appealInfo" v-on:saveReportListener="saveAppealReturn"></addReportModal>
    <addFollowModal v-bind:followModal="appealInfo" v-on:saveFollowListener="saveAppealReturn"></addFollowModal>
    <remindExamine v-bind:remindExamineVal="remindExamineVal"></remindExamine>
    <copyReport v-bind:copyReportModal="copyContent"></copyReport>
    <batchSaveModal v-on:batchSaveListener="batchSave"></batchSaveModal>
    <CusPreDetailModal ref="cusPreDetailRef" v-bind:cusPreId="cusPreId"></CusPreDetailModal>
  </div>
</template>

<script>
import batchSaveModal from "./batchSaveModal.vue";
import Modal from "../common/modal.vue";
import addAppealModal from "./addAppeal.vue";
import addReportModal from "./addReport.vue";
import addFollowModal from "./addFollow.vue";
import remindExamine from "./remindExamine.vue";
import dataTable from "../../constants/tableConfig.js";
import { formatDate } from "../../assets/js/date.js";
import copyReport from "./copyReport.vue";
import CusPreDetailModal from "./cusPreDetailModal.vue";
export default {
  data() {
    return {
      params: {
        pageSize: 10,
        pageNo: 1,
        userId: window.localStorage.getItem("1_userId"),
        searchContent: "",
        confirmStatus: "",
        createTimeBefore: "",
        createTimeAfter: "",
        premisesName: "",
        customerStatus: "",
        storeOrGroup: "",

      },
      customerPremisesList: [],
      customerArray: [],
      confirmArray: [],
      appealInfo: {
        cusPremisesId: "",
      },
      //	userAuthResources: window.localStorage.getItem("userAuthResources"),
      tableConfig: [],
      remindExamineVal: {
        id: "",
        name: "",
        phone: "",
        project: "",
        time: "",
        list: [],
      },
      copyContent: "报备项目：",
      cusPreId: "",
      exportUrl: "",
    };
  },
  components: {
    batchSaveModal,
    Modal,
    addAppealModal,
    addReportModal,
    addFollowModal,
    dataTable,
    remindExamine,
    copyReport,
    CusPreDetailModal,
  },
  mounted: function() {
    this.list(0);
    this.customerStatuList();
    this.confirmStatuList();
    dataTable.config.table = this;
    this.tableConfig = dataTable.config.cusPreColumns;
  },
  methods: {
    toDetail: function(id) {
      this.cusPreId = id;
      $("#cusPreDetailModal").modal("show");
      this.$refs.cusPreDetailRef.initData(id);
    },
    openBatchSaveModal() {
      $("#batchSaveModal").modal("show");
    },
    batchSave() {
      this.list(0);
    },
    list: function(type) {
      //加载数据
      var _self = this;
      //判断点查询按钮时，将当前页和条数设置为默认
      if (type == "1") {
        _self.params.pageNo = "1";
        _self.params.pageSize = "10";
      }
      var url = this.utilHelper.apiUrl + "/api/getCPPage";
      var body = {};
      body.params = _self.params;
      _self.$http.post(url, body).then(
        (response) => {
          var body = response.body.resData;
          if (body.result == 1) {
            var total = body.cpDtoPage.total;
            _self.customerPremisesList = body.cpDtoPage.rows;
            for (var ii = 0; ii < _self.customerPremisesList.length; ii++) {
              var record = _self.customerPremisesList[ii];
              var commissionAmount = record.commissionAmount;
              var customerStatus = record.customerStatus;
              var commissionStatus = record.commissionStatus;
              var CommissionIsShow = record.commissionIsShow;
              //非缴定、已结佣状态的记录,佣金金额统一设置为待定
              if (
                (commissionAmount &&
                  (customerStatus == 5 || customerStatus == 7)) ||
                CommissionIsShow == "1"
              ) {
                record.commissionAmount = _self.changeToDecimal(
                  record.commissionAmount,
                  2
                );
                record.reward = _self.changeToDecimal(record.reward, 2);
              } else {
                record.commissionAmount = "待定";
              }
              if (
                commissionAmount &&
                (customerStatus == 5 ||
                  customerStatus == 6 ||
                  customerStatus == 7)
              ) {
                record.reward = _self.changeToDecimal(record.reward, 2);
              } else {
                record.reward = "0";
              }

              //非已结佣记录的发放状态统一设置为待发放
              var payStatus = "待发放";
              if (commissionStatus == 1) {
                payStatus = "已发放";
              }
              if (CommissionIsShow == 1) {
                payStatus = "";
              }
              record.payStatus = payStatus;
            }
            var current = body.cpDtoPage.pageNumber;
            layui.laypage.render({
              elem: $("#laypage_div"), //容器。值支持id名、原生dom对象，jquery对象,
              //		    pages: totalPages, //总页数
              limit: 10,
              curr: current,
              count: total,
              theme: "#f87242;", //皮肤
              first: "首页", //若不显示，设置false即可
              last: "尾页", //若不显示，设置false即可
              prev: "上一页", //若不显示，设置false即可
              next: "下一页", //若不显示，设置false即可
              layout: ["prev", "page", "next", "skip", "count"],

              jump: function(obj, first) {
                if (!first) {
                  _self.params.pageNo = obj.curr;
                  _self.list(0);
                }
              },
            });
          } else {
            //layer.alert("系统异常!");
          }
        },
        (response) => {
          console.log(response);
        }
      );
    },
    exportList: function (){
      var loadIndex = layer.load();
      //加载数据
      var _self = this;
      var body = {};
      body.params = _self.params;
      console.log(body.params);
      var url = this.utilHelper.apiUrl + "/api/channelreport/exportCPPage";
      _self.$http
          .get(url, { params: body.params, responseType: "blob" })
          .then((response) => {
            layer.close(loadIndex);
            _self.exportBtnShow = true;
            const blob = new Blob([response.body], {
              type: "application/vnd.ms-excel", // 将会被放入到blob中的数组内容的MIME类型
            });
            const objectUrl = URL.createObjectURL(blob);
            _self.exportUrl = objectUrl;
            layer.msg("内容已生成,请【点击下载】下载!", {
              time: 2000
            });
          });
    },
    customerStatuList: function() {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/common/getEnum/CustomerStatusEnum";
      var findStatusParams = {
        //flag:'-2'
      };
      var body = {};
      body.params = findStatusParams;
      _self.$http.get(url, body).then(
        (response) => {
          _self.customerArray = response.body.data;
        },
        (response) => {
          //layer.alert("系统异常!");
        }
      );

      /*	*/
    },
    reSubmit: function(cusPremisesId, premisesId) {
      var _self = this;
      //申诉
      console.info(cusPremisesId + "=" + premisesId);
      var url = this.utilHelper.apiUrl + "/api/getPremisesDetail";
      var body = {
        params: {
          id: premisesId,
        },
      };
      _self.$http.post(url, body).then(
        (response) => {
          if (!response.body.resData.detailResDto) {
            layer.alert("楼盘已删除!");
          } else {
            this.appealInfo.cusPremisesId = cusPremisesId;
            $("#addAppealModal").modal("show");
          }
        },
        (response) => {
          //layer.alert("系统异常!");
        }
      );
    },
    toReport: function(cusPremisesId) {
      //重新报备 ，当状态为已过报备保护期  和 已过带看保护期时  可以执行操作
      this.appealInfo.cusPremisesId = cusPremisesId;
      $("#addReportModal").modal("show");
    },
    toFollow: function(cusPremisesId) {
      //经纪人填写跟进
      this.appealInfo.cusPremisesId = cusPremisesId;
      $("#addFollowModal").modal("show");
    },
    changeToDecimal(value, point) {
      var f_x = parseFloat(value);
      if (isNaN(f_x)) {
        value = "0";
      }
      var f_x = Math.round(value * 100) / 100;
      var s_x = f_x.toString();
      var pos_decimal = s_x.indexOf(".");
      if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += ".";
      }
      while (s_x.length <= pos_decimal + point) {
        s_x += "0";
      }
      return s_x;
    },
    saveAppealReturn() {
      this.list();
    },
    confirmStatuList: function() {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/common/getEnum/ConfirmStatusEnum";
      var findStatusParams = {};
      var body = {};
      body.params = findStatusParams;
      _self.$http.get(url, body).then(
        (response) => {
          _self.confirmArray = response.body.data;
        },
        (response) => {
          //layer.alert("系统异常!");
        }
      );

      /*	*/
    },
    toRemindExamine: async function(data) {
      let value = JSON.parse(data);
      this.remindExamineVal.id = value.id;
      this.remindExamineVal.name = value.name;
      this.remindExamineVal.phone = value.mobile;
      this.remindExamineVal.project = value.premisesName;
      this.remindExamineVal.time = value.hopeVisitTime;
      let url = this.utilHelper.apiUrl + "/api/listEstateAdviserByPremisesId";
      let body = {};
      body.params = {
        premisesId: value.premisesId,
      };
      let list = await this.$http.post(url, body);
      this.remindExamineVal.list = list.body.resData;
      $("#remindExamine").modal("show");
    },
    toCopy(cusPre) {
      var _self = this;
      let visitTime = "";
      let createTime = "";
      if (cusPre.hopeVisitTime) {
        visitTime = formatDate(cusPre.hopeVisitTime, "yyyy-MM-dd hh:mm:ss");
      }
      if (cusPre.createTime) {
        createTime = formatDate(cusPre.createTime, "yyyy-MM-dd hh:mm:ss");
      }
      _self.copyContent =
        cusPre.premisesName +
        "\r\n" +
        "客户姓名：" +
        cusPre.name +
        "\r\n" +
        "客户性别：" +
        cusPre.genderName +
        "\r\n" +
        "客户号码：" +
        cusPre.mobile +
        "\r\n" +
        "中介机构门店：" +
        cusPre.staffCompanyName +
        " " +
        cusPre.staffStoreName +
        " " +
        cusPre.staffGroupName +
        "\r\n" +
        "中介经纪人：" +
        cusPre.staffName +
        "\r\n" +
        "经纪人电话：" +
        cusPre.staffPhone +
        "\r\n" +
        "预计到访时间：" +
        visitTime +
        "\r\n" +
        "报备时间：" +
        createTime +
        "\r\n";

      var url = this.utilHelper.apiUrl + "/api/getReportModelInfoList";
      var body = {};
      body.params = {
        reportId: cusPre.id,
        premisesId: cusPre.premisesId,
        mobile: cusPre.mobile,
        agencyName: cusPre.staffName,
        agencyPhone: cusPre.staffPhone,
        premisesName: cusPre.premisesName,
        customerName: cusPre.name,
        genderName: cusPre.genderName,
        storeName:
          cusPre.staffCompanyName +
          " " +
          cusPre.staffStoreName +
          " " +
          cusPre.staffGroupName,
        visitTime: visitTime,
        createTime: createTime,
        recommenderUuid: cusPre.recommenderUuid,
      };
      _self.$http.post(url, body).then(
        (response) => {
          var resBody = response.body;

          if (resBody.result == "1") {
            if (resBody.resData.repotModelDetail) {
              _self.copyContent = resBody.resData.repotModelDetail;
            }
          }
          this.copy();
        },
        (response) => {
          this.copy();
        }
      );
    },
    copy() {
      this.$copyText(this.copyContent).then(
        function(e) {
          layer.msg("复制成功");
        },
        function(e) {
          layer.msg("复制失败，请手动复制");
        }
      );
    },
  },
};
</script>
